/**
 * 
 */
package com.lanswon.common.staticLoad;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.lanswon.common.util.PropertiesUtils;

/**
 * 
 * @ClassName: StaticLoadController.java
 * @Description: 该类的功能描述
 *
 * @version: v1.0.0
 * @author: zm
 * @date: 2018年6月8日 下午1:14:17
 *
 */

public class ImgLoad extends HttpServlet {

	@Override
	public void init() throws ServletException {
		PropertiesUtils.load("/config/system.properties");
		String localhost = System.getProperty("catalina.home") + PropertiesUtils.get("tomcat")
				+ PropertiesUtils.get("img");
		// localhost =
		// "C:\\Users\\lanswon\\eclipse-workspace\\qzsmk\\WebContent\\static\\img";
		String driver = PropertiesUtils.get("DRIVER");
		String url = PropertiesUtils.get("URL");
		String user = PropertiesUtils.get("USERNAME");
		String password = PropertiesUtils.get("PASSWORD");
		Connection conn = null;
		Statement statement = null;
		ResultSet rs = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			statement = conn.createStatement();
			rs = statement.executeQuery("select * from t_image");
			while (rs.next()) {
				String fileName = rs.getString(2);
				InputStream in = rs.getBlob(5).getBinaryStream();
				File file = new File(localhost + "\\" + fileName);
				if (!file.exists()) {
					// 先得到文件的上级目录，并创建上级目录，在创建文件
					file.getParentFile().mkdir();
					try {
						// 创建文件
						file.createNewFile();

					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				byte[] bytes = new byte[1024];
				OutputStream out = new FileOutputStream(file);
				while (in.read(bytes) != -1) {
					out.write(bytes);
				}
				out.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (statement != null) {
					statement.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

}
